package com.srp.backend.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 文件下载服务
 */
@Service
public class FileDownloadService {

    @Value("${app.output-structure-path:./output_structure/}")
    private String outputStructurePath;

    /**
     * 根据文件名加载文件
     * 
     * @param fileName 文件名，例如 result.docx 或 result.xlsx
     * @return 文件资源
     * @throws IOException 如果文件不存在或无法读取
     */
    public Resource loadFileByName(String fileName) throws IOException {
        Path filePath = Paths.get(outputStructurePath).resolve(fileName).normalize();
        Resource resource = new UrlResource(filePath.toUri());

        if (resource.exists() && resource.isReadable()) {
            return resource;
        } else {
            throw new IOException("文件不存在或无法读取: " + fileName);
        }
    }

    /**
     * 加载结果Word文件
     * 
     * @return 文件资源
     * @throws IOException 如果文件不存在或无法读取
     */
    public Resource loadResultWordFile() throws IOException {
        return loadFileByName("result.docx");
    }

    /**
     * 加载结果Excel文件
     * 
     * @return 文件资源
     * @throws IOException 如果文件不存在或无法读取
     */
    public Resource loadResultExcelFile() throws IOException {
        return loadFileByName("result.xlsx");
    }

    /**
     * 获取可用的结果文件列表
     * 
     * @return 可下载文件信息列表
     */
    public Map<String, Object> getResultFiles() {
        Path rootPath = Paths.get(outputStructurePath);
        File rootDir = rootPath.toFile();

        if (!rootDir.exists() || !rootDir.isDirectory()) {
            throw new RuntimeException("输出目录不存在");
        }

        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> files = new ArrayList<>();

        // 检查Word文件
        File wordFile = new File(rootDir, "result.docx");
        if (wordFile.exists()) {
            Map<String, Object> fileInfo = new HashMap<>();
            fileInfo.put("type", "word");
            fileInfo.put("filename", "result.docx");
            fileInfo.put("size", wordFile.length());
            fileInfo.put("downloadUrl", "/api/download/result/word");
            files.add(fileInfo);
        }

        // 检查Excel文件
        File excelFile = new File(rootDir, "result.xlsx");
        if (excelFile.exists()) {
            Map<String, Object> fileInfo = new HashMap<>();
            fileInfo.put("type", "excel");
            fileInfo.put("filename", "result.xlsx");
            fileInfo.put("size", excelFile.length());
            fileInfo.put("downloadUrl", "/api/download/result/excel");
            files.add(fileInfo);
        }

        result.put("files", files);

        return result;
    }

    /**
     * 加载Word文件作为资源
     * 
     * @param uuid 文件处理的UUID
     * @return 资源对象
     * @throws Exception 如果文件不存在或无法加载
     */
    public Resource loadWordFileAsResource(String uuid) throws Exception {
        Path wordFilePath = Paths.get(outputStructurePath + uuid + "/result.docx");
        return loadFileAsResource(wordFilePath);
    }

    /**
     * 加载Excel文件作为资源
     * 
     * @param uuid 文件处理的UUID
     * @return 资源对象
     * @throws Exception 如果文件不存在或无法加载
     */
    public Resource loadExcelFileAsResource(String uuid) throws Exception {
        Path excelFilePath = Paths.get(outputStructurePath + uuid + "/result.xlsx");
        return loadFileAsResource(excelFilePath);
    }

    /**
     * 加载可视化图片作为资源
     * 
     * @param uuid 文件处理的UUID
     * @param page 页码
     * @return 资源对象
     * @throws Exception 如果文件不存在或无法加载
     */
    public Resource loadVisualImageAsResource(String uuid, int page) throws Exception {
        Path imagePath = Paths.get(outputStructurePath + uuid + "/page" + page + "_visual.png");
        return loadFileAsResource(imagePath);
    }

    /**
     * 获取指定UUID目录下可下载的文件列表
     * 
     * @param uuid 文件处理的UUID
     * @return 可下载文件信息列表
     */
    public Map<String, Object> getDownloadableFiles(String uuid) {
        Path dirPath = Paths.get(outputStructurePath + uuid);
        File dir = dirPath.toFile();

        if (!dir.exists() || !dir.isDirectory()) {
            throw new RuntimeException("指定的UUID目录不存在");
        }

        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> files = new ArrayList<>();

        // 检查Word文件
        File wordFile = new File(dir, "result.docx");
        if (wordFile.exists()) {
            Map<String, Object> fileInfo = new HashMap<>();
            fileInfo.put("type", "word");
            fileInfo.put("filename", "result.docx");
            fileInfo.put("size", wordFile.length());
            fileInfo.put("downloadUrl", "/api/download/word/" + uuid);
            files.add(fileInfo);
        }

        // 检查Excel文件
        File excelFile = new File(dir, "result.xlsx");
        if (excelFile.exists()) {
            Map<String, Object> fileInfo = new HashMap<>();
            fileInfo.put("type", "excel");
            fileInfo.put("filename", "result.xlsx");
            fileInfo.put("size", excelFile.length());
            fileInfo.put("downloadUrl", "/api/download/excel/" + uuid);
            files.add(fileInfo);
        }

        // 检查可视化图片
        List<Map<String, Object>> visualImages = new ArrayList<>();
        File[] allFiles = dir.listFiles();
        if (allFiles != null) {
            for (File file : allFiles) {
                if (file.getName().matches("page\\d+_visual\\.png")) {
                    Map<String, Object> imageInfo = new HashMap<>();
                    String pageName = file.getName();
                    int pageNum = Integer.parseInt(pageName.substring(4, pageName.indexOf("_visual")));

                    imageInfo.put("type", "image");
                    imageInfo.put("filename", pageName);
                    imageInfo.put("page", pageNum);
                    imageInfo.put("size", file.length());
                    imageInfo.put("downloadUrl", "/api/download/visual/" + uuid + "/" + pageNum);
                    visualImages.add(imageInfo);
                }
            }
        }

        result.put("uuid", uuid);
        result.put("documents", files);
        result.put("images", visualImages);

        return result;
    }

    /**
     * 加载文件作为资源
     * 
     * @param filePath 文件路径
     * @return 资源对象
     * @throws Exception 如果文件不存在或无法加载
     */
    private Resource loadFileAsResource(Path filePath) throws Exception {
        try {
            Resource resource = new UrlResource(filePath.toUri());
            if (resource.exists()) {
                return resource;
            } else {
                throw new RuntimeException("文件不存在: " + filePath);
            }
        } catch (MalformedURLException ex) {
            throw new RuntimeException("文件路径错误: " + filePath, ex);
        }
    }
}